package com.feature.shop.front.gateway.util;

import org.apache.http.HttpHeaders;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;

import com.alibaba.fastjson2.JSON;
import com.feature.core.constant.Constants;
import com.feature.core.domain.Response;

import reactor.core.publisher.Mono;

public class WebFluxUtil {
	/**
	 * 设置webflux模型响应
	 *
	 * @param response ServerHttpResponse
	 * @param value    响应内容
	 * @return Mono<Void>
	 */
	public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value) {
		return webFluxResponseWriter(response, HttpStatus.OK, value, Constants.FAIL);
	}

	/**
	 * 设置webflux模型响应
	 *
	 * @param response ServerHttpResponse
	 * @param code     响应状态码
	 * @param value    响应内容
	 * @return Mono<Void>
	 */
	public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value, String code) {
		return webFluxResponseWriter(response, HttpStatus.OK, value, code);
	}

	/**
	 * 设置webflux模型响应
	 *
	 * @param response ServerHttpResponse
	 * @param status   http状态码
	 * @param code     响应状态码
	 * @param value    响应内容
	 * @return Mono<Void>
	 */
	public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, HttpStatus status, Object value, String code) {
		return webFluxResponseWriter(response, MediaType.APPLICATION_JSON_VALUE, status, value, code);
	}

	/**
	 * 设置webflux模型响应
	 *
	 * @param response    ServerHttpResponse
	 * @param contentType content-type
	 * @param status      http状态码
	 * @param code        响应状态码
	 * @param value       响应内容
	 * @return Mono<Void>
	 */
	public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, String contentType, HttpStatus status, Object value, String code) {
		response.setStatusCode(status);
		response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
		Response<?> result = Response.fail(code, value.toString());
		DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes());
		return response.writeWith(Mono.just(dataBuffer));
	}
}
